Currently, I have an array r[1] to r[12].
Now, I need to print it like this:
r[10] r[11] r[12]
r[7] r[8] r[9]
r[4] r[5] r[6]
r[1] r[2] r[3]
for (int i = 0; i < 4; i++){
for(int j = 0; j < 3; j++){
print("%d", r[ 12 - (i * 3) + j]);
}
}
If you need any other numbers than you could generalize the solution
for (int i = 0; i < count / interval; i++){
for(int j = 0; j < interval; j++){
print("%d", r[ count - (i * interval) + j]);
}
supposing you've got an array with n elements and you want to show them in row of 3 elements, you could proceed in this way (in php):
// this is your array, it starts with 1 and could end with n (but it must be divisible by 3)
$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
// check if the number of the elements is ok for the script
if (count($array) % 3) {
echo "The array must be divisible for the number of the element in a row!";
exit;
}
// for each row, from 1 to number of the elements in array...
for ($row = 1; $row <= count($array) / 3; $row++){
// ... and for each column (with a max of 3 columns)
for($column = 0; $column < 3; $column++){
// print out the last element, less current row multipled by 3 plus the number of the column (which was started with 1).
echo $array[count($array) - ($row * 3) + $column] . " ";
}
// another row is finished, move the cursor to the next line
echo "<br />";
}
Related
Given n = 3 dogs and m = 3 pairs of enemies, a = [1, 2, 3] and b = [3, 3, 1], dog 1 is the enemy of dog 3, and dog 3 is the enemy of dogs 1 and 2. Because 3 is an enemy of both 1 and 2, it must be in its own container. dogs 1 and 2 can be together or separately. There are 4 possible groups: {1, 2} ,{1}, {2}, {3}. Note that the intervals are along the original line of dogs numbered consecutively from 1 to n, i.e. [1, 2, 3] in this case. The dogs cannot be reordered and dogs cannot be skipped, e.g. {2, 1} and {1, 3} are invalid.
So given the following:
case #1:
n = 5
m = 2
a = (1,2)
b = (3,5)
Result is: Total of 11 groups can be formed.
case #2
n = 8
m = 4
a = (2,3,4,3)
b = (8,5,6,4)
Result is: Total of 18 groups can be formed.
Here's my code:
function countSubstrings($n, $a, $b) {
$tokenArr = array();
$x = 1;
while ($x <= $n){
$tokenArr[] = $x;
$x++;
}
$first = 0;
$last = $n - 1;
$outArr = array();
$pointer = 0;
/* generate groups left to right */
for ($i = $first; $i <= $last; $i++) {
$outArr[$pointer][] = $tokenArr[$i];
$tokenString = $tokenArr[$i];
$pointer++;
for ($j = $i + 1; $j <= $last; $j++) {
$tokenString .= $tokenArr[$j];
$outArr[$pointer] = str_split($tokenString);
$pointer++;
}
}
/* find the enemeies */
$intersects = array();
for($k = 0; $k < count($outArr); $k++){
if (count(array_intersect($outArr[$k], $a)) > 1 || count(array_intersect($outArr[$k], $b)) > 1) {
$intersects[] = $outArr[$k];
}
}
/* remove first and last items which are basically equal to $a and $b */
$intersects = array_slice($intersects, 1, -1);
/* remove the enemeies from generated groups */
foreach ($outArr as $keya => $valuea) {
if (in_array($valuea, $intersects)) {
unset($outArr[$keya]);
}
}
return count($outArr);
}
So far my code works in case: #1 but fails on #2.
The intersect logic seems to be incorrect to me as we have to check if the relationship formed by [a , b], for example, [1,2] exists in $outArr or not. Current check of count(array_intersect($outArr[$k], $a)) > 1 does not care about that. It rather checks if any element in $outArr[$k] is present in $a or not.
So, change the current logic from:
/* find the enemeies */
$intersects = array();
for($k = 0; $k < count($outArr); $k++){
if (count(array_intersect($outArr[$k], $a)) > 1 || count(array_intersect($outArr[$k], $b)) > 1) {
$intersects[] = $outArr[$k];
}
}
/* remove first and last items which are basically equal to $a and $b */
$intersects = array_slice($intersects, 1, -1);
to
$intersects = array();
foreach($a as $index => $val1){
$val2 = $b[$index];
foreach($outArr as $current_group){
if(in_array($val1,$current_group) && in_array($val2,$current_group)){ // check if both exist as they are enemies
$intersects[] = $current_group;
}
}
}
Demo: https://3v4l.org/Q2rnP
In the above code, we:
loop through all elements of $a and simultaneously with $b with the help of $index in foreach.
Check if for the current group in $outArr, whether both $a[$index](a.k.a $val1) and $b[$index](a.k.a $val2) exist in the group or not.
If both exist in current group, we put them under intersect as they are enemies. Your rest of the logic is correct.
Efficient Solution:
We have to exploit this line:
A group is defined as an interval (x, y) such that all dogs in the range from x to y form a group.
This means that we need to look at subarrays(as you correctly judged) instead of subsequences.
Now, we loop from 1 to N and if we find a number which has an enemy on the left, we can only form the next groups from that number + 1 onwards. Anything before them can't be included anyway since we are looking at subarrays.
For example, let's assume 5 is an enemy of 3 in a line of 1 to 5 and no other enemies are present. So, group formations would look like below.
Representation:
1 2 3 4 5
-1 -1 5 -1 3
|___|
|___|___|
|___|___|___|
|___|
|___|___|
|___|
|___| // the connection/group (4,5) remains and breaks everything before 4 since 3 is an enemy of 5 and we are looking for subarrays. So everything before 4 is disconnected anyway.
So, our next starting animal/dog to look from is 4.
For each enemy/animal, we maintain the nearest enemy on the left if present. If present, we update the next animal to look from for groups as proved above. In the below code, $prev_start is the variable that maintains the next animal to look from.
In order to get nearest enemy on the left for each animal, we preprocess the enemy details as follows:
Preprocessing:
$enemies = array_combine(range(1,$n),array_fill(0,$n,-1)); // nothing tricky, just generates an array filled with sequential numbers as keys and sets it's value as -1
foreach($a as $index => $enemy_1){
$enemy_2 = $b[$index];
if($enemy_1 < $enemy_2){
$enemies[$enemy_2] = max($enemies[$enemy_2],$enemy_1);
}else if($enemy_2 < $enemy_1){
$enemies[$enemy_1] = max($enemies[$enemy_1],$enemy_2);
}
}
Computation:
$prev_start = 1;
$count = 0;
for($i=1;$i<=$n;++$i){
if($enemies[$i] !== -1){
$prev_start = max($enemies[$i] + 1,$prev_start);
}
$count += ($i - $prev_start + 1);
}
Since we preprocessed enemy details, we update $prev_start accordingly from where we have to start counting for groups again.
$count += ($i - $prev_start + 1); simply counts the number of groups(subarrays) to consider for counting.
Time complexity: O(m + n) where m is number of pairs and n is the number of dogs/animals.
Space complexity: O(n) where n is the number of dogs/animals.
Full Code:
<?php
function countSubarrays($n, $a, $b) {
$enemies = array_combine(range(1,$n),array_fill(0,$n,-1)); // nothing tricky, just generates an array filled with sequential numbers as keys and sets it's value as -1
foreach($a as $index => $enemy_1){
$enemy_2 = $b[$index];
if($enemy_1 < $enemy_2){
$enemies[$enemy_2] = max($enemies[$enemy_2],$enemy_1);
}else if($enemy_2 < $enemy_1){
$enemies[$enemy_1] = max($enemies[$enemy_1],$enemy_2);
}
}
$prev_start = 1;
$count = 0;
for($i=1;$i<=$n;++$i){
if($enemies[$i] !== -1){
$prev_start = max($enemies[$i] + 1,$prev_start);
}
$count += ($i - $prev_start + 1);
}
return $count;
}
Demo: https://3v4l.org/1W26C
I seen in the selection sort if inner equals to minimum value it will be swapping them. but why you do it?
I just added the if statement for swapping if $inner = $min so why swapping them because they are the same index!. So why you do it?!!
The condition is : if $inner = $minimum (Don't swap). else they are not euqal (swap).
this is the code.
<?php
$a = array(10,9,8,7,6,5,4,3,2,1);
$num = sizeof($a);
$comp = 0;
$swap = 0;
for ($i=0; $i < $num; $i++) {
echo "$a[$i] | ";
}
echo "<br>";
for ($in=0; $in < $num; $in++) {
$min = $in;
for ($i=$in+1; $i < $num; $i++) {
if ($a[$i] < $a[$min]) {
$min = $i;
}
$comp++;
}
if ($in != $min) {
$past = $a[$min];
$a[$min] = $a[$in];
$a[$in] = $past;
$swap++;
}
}
for ($i=0; $i < $num; $i++) {
echo "$a[$i] | ";
}
echo "<br> comp : $comp , swap : $swap";
?>
No. Time complexity doesn't depend upon number of swaps you did but on number of iterations for checking.
Lets take an example.,
1 4 9 3 0 8 5
You're saying that you'll iterate the whole array and find the lowest(minimum) number and you'll swap it with current index if both are not equal.
That means,
Your sorted array: 0 4 9 3 1 8 5
But it's not sorted. It means it is sorted upto 0th [1st number] index only.
You've to repeat it the same from 2nd index.
Now, lets find out the actual time complexity.
As you iterate for every index (let's take as 'i'), it is O(N) for outer loop and you'll iterate inner loop from i+1 (let's take as 'j') and it's O(N) for inner loop.
So O(N)*O(N)=O(N^2)
If you still have any doubt, lets take iterations of j that is,
for i=0, j iterates from 1 -> N
for i=1, j iterates from 2 -> N
for i=2, j iterates from 3 -> N and so on...
so = (N-1) + (N-2) + (N-3) + (N-4) ......+ 1
=> (N (N-1)) / 2
= O(N^2)
The problem statement is as following:
A particular kind of coding which we will refer to as "MysteryCode" is a binary system of encoding in which two successive values, differ at exactly one bit, i.e. the Hamming Distance between successive entities is 1. This kind of encoding is popularly used in Digital Communication systems for the purpose of error correction.
LetMysteryCodes(N)represent the MysteryCode list for N-bits.
MysteryCodes(1) = 0, 1 (list for 1-bitcodes,in this order)
MysteryCodes(2) = 00, 01, 11, 10 (list for 2-bitcodes,in this order)
MysteryCodes(3) =000, 001, 011, 010,110, 111, 101, 100 (list for 3-bitcodes,in this order)
There is a technique by which the list of (N+1) bitcodescan be generated from (N)-bitcodes.
Take the list of N bitcodesin the given order and call itList-N
Reverse the above list (List-N), and name the new reflected list: Reflected-List-N
Prefix each member of the original list (List-N) with 0 and call this new list 'A'
Prefix each member of the new list (Reflected-List-N) with 1 and call this new list 'B'
The list ofcodeswith N+1 bits is the concatenation of Lists A and B.
A Demonstration of the above steps: Generating the list of 3-bitMysteryCodesfrom 2-BitMysteryCodes
2-bit list ofcodes:00, 01, 11, 10
Reverse/Reflect the above list:10, 11, 01, 00
Prefix Old Entries with 0:000, 001, 011, 010
Prefix Reflected List with 1:110, 111, 101, 100
Concatenate the lists obtained in the last two steps:000, 001, 011, 010, 110, 111, 101, 100
Your Task
Your task is to display the last N "MysteryCodes" from the list of MysteryCodes for N-bits. If possible, try to identify a way in which this list can be generated in a more efficient way, than iterating through all the generation steps mentioned above.
More efficient or optimized solutions will receive higher credit.
Input Format
A single integer N.
Output Format
N lines, each of them with a binary number of N-bits. These are the last N elements in the list ofMysteryCodesfor N-bits.
Input Constraints 1 = N = 65
Sample Input 1
1
Sample Output 1
1
Explanation for Sample 1
Since N = 1, this is the (one) last element in the list ofMysteryCodesof 1-bit length.
Sample Input 2
2
Sample Output 2
11
10
Explanation for Sample 2 Since N = 2, these are the two last elements in the list ofMysteryCodesof 2-bit length.
Sample Input 3
3
Sample Output 3
111
101
100
$listN = 25;
$bits = array('0','1');
//check if input is valid or not
if(!is_int($listN))
{
echo "Input must be numeric!";
}
if($listN >= 1 && $listN <=65){
if($listN == 1){
echo '1'; exit;
}
ini_set('memory_limit', -1);
for($i=1; $i<=($listN - 1); $i++){
$reverseBits = array_reverse($bits);
$prefixBit = preg_filter('/^/', '0', $bits);
$prefixReverseBits = preg_filter('/^/', '1', $reverseBits);
$bits = array_merge($prefixBit, $prefixReverseBits);
unset($prefixBit, $prefixReverseBits, $reverseBits);
}
$finalBits = array_slice($bits, -$listN);
foreach($finalBits as $k=>$v){
echo $v."\n";
}
}
else{
echo "Invalid input!";
}
I have tried above solution, but didnt worked for input greater than 20.
for eg. If the input is 21, I got "Couldnt allocate memory" error.
It will be great if somebody figure out the optimized solutions...
The numbers follow a pattern which I transformed to below code.
Say given number is N
then create a N x N matrix and fill it's first column with 1's
and all other cells with 0's
Start from rightmost column uptil 2nd column.
For any column X start from bottom-most row and fill values like below:
Fill 2^(N - X + 1)/2 rows with 0's.
Fill 2^(N - X + 1) rows with 1's and then 0's alternatively.
Repeat step 2 till we reach topmost row.
Print the N x N matrix by joining the values in each row.
<?php
$listN = 3;
$output = [];
for ($i = 0; $i < $listN; $i++) {
$output[$i] = [];
for ($j = 0; $j < $listN; $j++) {
$output[$i][$j] = 0;
}
}
$output[$listN - 1][0] = 1;
for ($column = 1; $column < $listN; $column++) {
$zeroFlag = false;
for ($row = $listN - 1; $row >= 0;) {
$oneZero = 1;
if (!$zeroFlag) {
for ($k = 1; $k <= pow(2, $column) / 2 && $row >= 0; $k++) {
$output[$row][$listN - $column] = 0;
$row--;
$zeroFlag = true;
}
}
for ($k = 1; $k <= pow(2, $column) && $row >= 0; $k++) {
$output[$row][$listN - $column] = $oneZero;
$row--;
}
$oneZero = 0;
for ($k = 1; $k <= pow(2, $column) && $row >= 0; $k++) {
$output[$row][$listN - $column] = $oneZero;
$row--;
}
}
}
for ($i = 0; $i < $listN; $i++) {
$output[$i][0] = 1;
}
for ($i = 0; $i < $listN; $i++) {
print(join('', $output[$i]));
print("\n");
}
9 numbers. Count how often the sum of 3 consecutive numbers in this set of numbers equaled to 16:
2, 7, 7, 1, 8, 2, 7, 8, 7,
The answer is 2. 2 + 7 + 7 = 16 and 7 + 1 + 8 = 16
But I can't seem to get the answer, because I don't know how to "loop" back and skip the first number and do the process over.
How would one be able to solve this utilizing arrays, and how would one solve this without utilizing arrays?
The 9 numbers are randomly generated, and it has to stay that way, but for the sake of solving, I used seed of 3 using srand(3). This is my current code below:
<?php
srand(3);
$count = 1;
$answer = 0;
$num1 = 0;
$num2 = 0;
$num3 = 0;
for ($i = 0; $i < 9; $i++)
{
$num = rand(0, 9);
echo $num . ', ';
if ($count == 1)
$num1 = $num;
else if ($count == 2)
$num2 = $num;
else if ($count == 3)
{
$num3 = $num;
$count = 1;
}
if ($num1 + $num2 + $num3 == 16)
$answer++;
$count++;
}
echo '<br />*******' . $answer . '*******';
?>
Obviously this isn't the right answer because I had to do the check again, but skipping the first number, and so on and so forth until (the last indexed number - index 3)
Probably not the most efficient solution, but its hard to think at 11 at night:
$array = array(2, 7, 7, 1, 8, 2, 7, 8, 7);
$count = count($array);
for ($x = 0; $x < $count; $x++) {
$parts = array_chunk($array, 3);
foreach ($parts as $part) {
if (array_sum($part) == 16 && count($part) == 3) {
print_r($part);
}
}
array_shift($array);
}
Another solution which I think is the more efficient, logic similar to what #Jeroen Vannevel answered:
$array = array(2, 7, 7, 1, 8, 2, 7, 8, 7);
$count = count($array) - 2;
for ($x = 0; $x < $count; $x++) {
if ($array[$x] + $array[$x+1] + $array[$x+2] == 16) {
echo "{$array[$x]} + {$array[$x+1]} + {$array[$x+2]} = 16 <br />";
}
}
Not a PHP writer but this could be your approach:
Fill the array from indices 0 up to and including 8 with a random value.
Iterate from index 0 to index [length - 3]. (length is 9)
Calculate the sum of the values on index [currentIndex], [currentIndex + 1] and [currentIndex + 2].
Whenever the value of that sum equals 16, increment your [count] variable by 1.
What does it mean when there is a comma in the first parameter of a for loop?
For example:
for ($j=0, $n2=sizeof($quotes[$i]['methods']); $j<$n2; $j++) {
//
}
A comma in the first section of the loop just separates variable declarations.
Essentially it is just declaring two variables $j=0 and $n2=sizeof($quotes[$i]['methods']), but in the loop constructor instead of before the loop constructor.
PHP inherited C++-like syntax.
It is common for C++-like languages to have scope visibility for code blocks or control structures, like:
#include <iostream>
using namespace std;
int main() {
int a = 0; // main scope;
int b = 5; // main scope;
if(a != b){
int c = a + b; // if scope;
// a, b, c visible.
}
// a and b visible, but c - not visible.
for(int i = 10; i < 20; i++){
// for-loop scope:
// i, a and b visible
cout << "i: " << i << endl;
}
// a and b visible, but i - not visible.
return 0;
}
PHP has no such feature, but inherited syntax rules (and most of C++ code conventions).
<?php
header('Content-Type: text/plain');
for($i = 0, $j = 10; $i < 10; $i++, $j += 2){
echo "{$i} + {$j} = ", $i + $j, PHP_EOL;
}
?>
is equival to
<?php
header('Content-Type: text/plain');
$j = 10;
for($i = 0; $i < 10; $i++){
echo "{$i} + {$j} = ", $i + $j, PHP_EOL;
$j += 2;
}
?>
Variables $i and $j will be accessible everywhere after for-loop, but declaring them in for-loop header section might be done for obviosity (some people say, that those variables are definately used in this cycle). Also it is shorter.
NOTE: You may use , for every header section of for-loop too.
UPDv1:
for-loop declaration:
for(initialization_section; condition_section; post_execution_section){
// actions
}
Each of sections might contain expression, but can not contain other control structures.
1) initialization_section:
Should contain expressions to execute before loop starts.
If there is more than one separate expression, they should be separated by comma ,.
Executes before any of for-loop iterations.
for($i = 0, $j = 1; $i < 10; $i++){
echo "{$i} + {$j} = ", $i + $j, PHP_EOL;
}
Result:
0 + 1 = 1
1 + 1 = 2
2 + 1 = 3
3 + 1 = 4
4 + 1 = 5
5 + 1 = 6
6 + 1 = 7
7 + 1 = 8
8 + 1 = 9
9 + 1 = 10
2) condition_section:
Should contain expressions to check if loop continues or stops. If there is more than one separate action, they should be separated by comma ,.
Executes before every for-loop iteration.
for($i = 1, $j = 0; $i++, $j < 10; $j++){
echo "{$i} + {$j} = ", $i + $j, PHP_EOL;
}
Result:
2 + 0 = 2
3 + 1 = 4
4 + 2 = 6
5 + 3 = 8
6 + 4 = 10
7 + 5 = 12
8 + 6 = 14
9 + 7 = 16
10 + 8 = 18
11 + 9 = 20
Comma in this section of for-loop causes ignore of all previous expressions of this section, except the last one (as #icktoofay mentioned).
for($i = 0, $j = 1; $i < 1, $j < 5; $i++, $j++){
echo "{$i} + {$j} = ", $i + $j, PHP_EOL;
}
Result:
0 + 1 = 1
1 + 2 = 3
2 + 3 = 5
3 + 4 = 7
Regardless of $i < 1 is false for the second iteration. It might be used as default pre-execution statement.
3) post_execution_section:
Should contain expressions to execute after loop body actions are performed. If there is more than one separate action, they should be separated by comma ,.
Executes after every for-loop iteration.
for($i = 0; $i < 10; $i++, $i *= 2){
echo $i, PHP_EOL;
}
Result:
0
2
6
Also, each of for-loop sections might be empty (do nothing) with preserve of semicolon ; separators:
for(;;){
// infinite loop
}