Sorting and getting higest values codeigniter - php

I have a cloumn like token_number in table the values inserted in this row are like
token_number
1
2
3
15
4
5
6
14
7
8
18
10
11
9
etc..
I sort these values
1,2,3,4,5,6,7,8,9,10,11,14,15,18
I want to get the value 11 from this sorted array
ie the highest number with common difference 1
How to get 11 from this array?

Since the array is sorted, you can start from the bottom e loop it backwards:
$arr = // sorted array;
$max = null;
for( $i = count($arr) - 1 ; $i > 0 ; $i++ ){
if($arr[$i] - 1 == $arr[$i-1]){
$max = $arr[$i-1];
break;
}
}
if($max !== null){
echo "founded: " . $max;
}

You can find highest number with command difference as follow.
$arr= array(1,2,3,4,5,6,7,8,9,10,11,14,15,18);
$highestNo = null;
for($i=0 ;$i <= count($arr) - 1 ; $i++ ){
$diff = $arr[$i+1] - $arr[$i]; //check difference of current and next number
if($diff != 1){
$highestNo = $arr[$i];
break;
}
}
echo "Highest number with comman difference is: " . $highestNo;

Related

Can someone help me return a value?

I have created a loop which returns a random number between two values. Cool.
But now I want the script to return the following value too: The number of unique numbers between two similar numbers.
Example:
4
5
8
22
45
3
85
44
4
55
15
23
As you see there is a double which is the four and there are 7 numbers inbetween. So I would like the script to echo these numbers two so in this case it should echo 7 but if there are more doubles in the list it should echo all the numbers between certain doubles.
This is what I have:
for ($x = 0; $x <= 100; $x++) {
$min=0;
$max=50;
echo rand($min,$max);
echo "<br>";
}
Can someone help me or guide me? I'm learning :)
Thanks!
So You need to seperate script for three parts:
getting randoms and save them to array (name it 'result'),
analyze them,
print (echo) results
Simply - instead of printing every step of loop, save them to array(), exit loop, analyze every item with other, example:
take i element of list
check is i+j element is the same
if is it the same - save j-i to second array() (name it 'ranges')
And after this, print two arrays (named by me as 'result' and 'ranges')
UPDATE:
Here's solution, hope You enjoy:
$result = array(); #variable is set as array object
$ranges = array(); #same
# 1st part - collecting random numbers
for ($x = 0; $x < 20; $x++)
{
$min=0;
$max=50;
$result[] = rand($min,$max); #here's putting random number to array
}
$result_size = count($result); #variable which is containg size of $result array
# 2nd part - getting ranges between values
for ($i = 0; $i < $result_size; $i++)
{
for ($j = 0; $j < $result_size; $j++)
{
if($i == $j) continue; # we don't want to compare numbers with itself,so miss it and continue
else if($result[$i] == $result[$j])
{
$range = $i - $j; # get range beetwen numbers
if($range > 0 ) # this is for miss double results like 14 and -14 for same comparing
{
$ranges[$result[$i]] = $range;
}
}
}
}
#3rd part - priting results
echo("RANDOM NUMBERS:<br>");
foreach($result as $number)
{
echo ("$number ");
}
echo("<br><br>RANGES BETWEEN SAME VALUES:<br>");
foreach($ranges as $number => $range)
{
echo ("For numbers: $number range is: $range<br>");
}
Here's sample of echo ($x is set as 20):
RANDOM NUMBERS:
6 40 6 29 43 32 17 44 48 21 40 2 33 47 42 3 22 26 39 46
RANGES BETWEEN SAME VALUES:
For numbers: 6 range is: 2
For numbers: 40 range is: 9
Here is your fish:
Put the rand into an array $list = array(); and $list[] = rand($min,$max); then process the array with two for loops.
$min=0;
$max=50;
$list = array();
for ($x = 0; $x <= 100; ++$x) {
$list[] = rand($min,$max);
}
print "<pre>";print_r($list);print "</pre>";
$ranges = array();
$count = count($list);
for ($i = 0; $i < $count; ++$i) {
$a = $list[$i];
for ($j = $i+1; $j < $count; ++$j) {
$b = $list[$j];
if($a == $b) {
$ranges[] = $j-$i;
}
}
}
print "<pre>";print_r($ranges);print "</pre>";

PHP: for loop $i value turns zero if the number is greater

I want to turn the $i variable value to start counting from 1 if the given value is greater than 10:
here is what i am trying to achieve
<?php
$givenValue = 15; //number of x value
for ($i = 1; $i < $givenValue; $i++) {
if ($givenValue > 10){
$i = 1;
}
echo $i."<br>";
}
?>
This is how i want my result to look like
output: 1
output: 2
output: 3
output: 4
output: 5
output: 6
output: 7
output: 8
output: 9
output: 10
output: 1
output: 2
output: 3
output: 4
output: 5
in for loop body
Any help is welcome
You can use modulo calculation to get the result you want.
I also changed your if from $givenvalue to $i as $givenvalue will "always" be 10+.
$givenValue = 15; //number of x value
for ($i = 1; $i <= $givenValue; $i++) {
if ($i > 10){
Echo $i%10 . "\n";
}else{
echo $i . "\n";
}
}
https://3v4l.org/5afc5
Another option, if that is possible for you, is to start at zero and only use modulo calculation and add one to it to get the same result.
This also means I need to stop the loop at <$givenvalue as your original code shows.
$givenValue = 15; //number of x value
for ($i = 0; $i < $givenValue; $i++) {
Echo $i%10+1 . "\n";
}
https://3v4l.org/r0sgA
A method that uses less looping is to add 10 to the loop on each iteration and create the values using range().
Then add them to the array with array_merge, and output with implode.
$givenValue = 47; //number of x value
$breakpoint = 10;
$arr=[];
For($i = $breakpoint; $i< $givenValue;){
// Add new values from 1-$breakpoint in array
$arr = array_merge($arr, range(1,$breakpoint));
$i +=$breakpoint;
}
// Loop will exit before all values been collected
// Add the rest of the values
$arr = array_merge($arr, range(1,$givenValue-($i-10)));
// Echo the values in array
Echo implode("\n", $arr);
https://3v4l.org/jGsO4
Your code can be written like this:
<?php
$givenValue = 15; //number of x value
for ($i = 1; $i <= $givenValue; $i++)
{
if ($i > 10)
{
$i = 1;
$givenValue-=10;
}
echo "output: $i\n";
}
?>
http://sandbox.onlinephpfunctions.com/code/ed34d8dcd12a9a5a866b73338ad1209f55298519
You are resenting the counter, I would expect the behaviour you have. To do what you want add another counter to the mix
$j=1;
$givenValue = 15; //number of x value
for ($i = 1; $i <= $givenValue; $i++) {
if ($j > 10){
$j = 1;
}
echo $j."\n";
++$j;
}
You also had several missing ;
Output:
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
If you want to end on 5 you have to do 16 as the $givenValue or change it to <= less than or equal
See it here live
See what I have now, the $i variable counts to the $givenValue then the $j variable counts along side it, but with a range of 1-10 ( resets to 1 after 10 )

Selection sort best swapping case is not O(N) It is O(1) !!?

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)

Program to find X-numbers in an array

in an N numbers of array a number is a X-number if it is divisible by atleast one other number in the array. Program to find how many such numbers exists in an given array
example 1 : in array [1,2,3] , number of x-numbers is 2 ( 2 and 3 as they are divisible by number 1 )
example 2 : in array [2,3,5,8] , number of x-numbers is 1 ( 8 is divisible by 2 )
example 3 : in array [2,3,6,12] , number of x-numbers is 2 ( 6 is divisible by 2 and 3 , 12 is divisible by 2 and 3 and 6 )
I am using the below code, but i want to optimize it in a way if the array size increase the performance should not hamper :
$arr = array(2,3,6,12);
$count = 0;
function check_special_num($tnum, $tarr){
sort($tarr);
for($i=0;$i<sizeof($tarr);$i++){
if( $tnum % $tarr[$i] == 0 ){
return true;
}
}
return false;
}
for($i=0;$i<sizeof($arr);$i++){
$temp = $arr;
$num = $arr[$i];
array_splice($temp, $i, 1);
if( check_special_num( $num, $temp ) ){
$count += 1;
}
}
echo $count;
Coding language is PHP
It might be faster this way:
$arr = array(2,3,6,12);
function x_numbers_count($arr) {
$count = 0;
sort($arr);
foreach ($arr as $i => $number) {
for ($j = 0; $j < $i; $j++) {
if ($number % $arr[$j] == 0) {
$count++;
break;
}
}
}
return $count;
}
echo x_numbers_count($arr);
The main differences, which can be expected to improve performance:
the array is sorted only once, before beginning to work (this could also improve your own method, without changing anything else)
the search loop stops as soon as it is to reach the current investigated number
less variables are used

How do I distribute values of an array in three columns?

I need this output..
1 3 5
2 4 6
I want to use array function like array(1,2,3,4,5,6). If I edit this array like array(1,2,3), it means the output need to show like
1 2 3
The concept is maximum 3 column only. If we give array(1,2,3,4,5), it means the output should be
1 3 5
2 4
Suppose we will give array(1,2,3,4,5,6,7,8,9), then it means output is
1 4 7
2 5 8
3 6 9
that is, maximum 3 column only. Depends upon the the given input, the rows will be created with 3 columns.
Is this possible with PHP? I am doing small Research & Development in array functions. I think this is possible. Will you help me?
For more info:
* input: array(1,2,3,4,5,6,7,8,9,10,11,12,13,14)
* output:
1 6 11
2 7 12
3 8 13
4 9 14
5 10
You can do a loop that will automatically insert a new line on each three elements:
$values = array(1,1,1,1,1);
foreach($values as $i => $value) {
printf('%-4d', $value);
if($i % 3 === 2) echo "\n";
}
EDIT: Since you added more information, here's what you want:
$values = array(1,2,3,4,5);
for($line = 0; $line < 2; $line++) {
if($line !== 0) echo "\n";
for($i = $line; $i < count($values); $i+=2) {
printf('%-4d', $values[$i]);
}
}
And if you want to bundle all that in a function:
function print_values_table($array, $lines = 3, $format = "%-4d") {
$values = array_values($array);
$count = count($values);
for($line = 0; $line < $lines; $line++) {
if($line !== 0) echo "\n";
for($i = $line; $i < $count; $i += $lines) {
printf($format, $values[$i]);
}
}
}
EDIT 2: Here is a modified version which will limit the numbers of columns to 3.
function print_values_table($array, $maxCols = 3, $format = "%-4d") {
$values = array_values($array);
$count = count($values);
$lines = ceil($count / $maxCols);
for($line = 0; $line < $lines; $line++) {
if($line !== 0) echo "\n";
for($i = $line; $i < $count; $i += $lines) {
printf($format, $values[$i]);
}
}
}
So, the following:
$values = range(1,25);
print_array_table($values);
Will output this:
1 10 19
2 11 20
3 12 21
4 13 22
5 14 23
6 15 24
7 16 25
8 17
9 18
One solution is to cut the array into chunks, representing the columns, and then print the values in row order:
$cols = array_chunk($arr, ceil(count($arr)/3));
for ($i=0, $n=count($cols[0]); $i<$n; $i++) {
echo $cols[0][$i];
if (isset($cols[1][$i])) echo $cols[1][$i];
if (isset($cols[2][$i])) echo $cols[2][$i];
}
If you don’t want to split your array, you can also do it directly:
for ($c=0, $n=count($arr), $m=ceil($n/3); $c<$m; $c++) {
echo $arr[$c];
for ($r=$m; $r<$n; $r+=$m) {
echo $arr[$c+$r];
}
}
$a = array(1,2,3,4,5);
"{$a[0]} {$a[1]} {$a[2]}\n{$a[3]} {$a[4]}";
or
$a = array(1,2,3,4,5);
"{$a[0]} {$a[1]} {$a[2]}".PHP_EOL."{$a[3]} {$a[4]}";
or
$a = array(1,2,3,4,5);
$second_row_start = 3; // change to vary length of rows
foreach( $a as $index => $value) {
if($index == $second_row_start) echo PHP_EOL;
echo "$value ";
}
or, perhaps if you want a longer array split into columns of 3?
$a = array(1,2,3,4,5,6,7,8,9,10,11,12,13);
$row_length = 3; // change to vary length of rows
foreach( $a as $index => $value) {
if($index%$row_length == 0) echo PHP_EOL;
echo "$value ";
}
which gives
1 2 3
4 5 6
7 8 9
10 11 12
13
one solution is :
your array has N elements, and you want 3 columns, so you can get the value of each cell with $myarray[ column_index + (N/3) + line_index ] (with one or two loops for columns and lines, at least for lines)
I hope this will help you
Bye
Here's something I whipped up. I'm pretty sure this could be more easily accomplished if you were using HTML lists, I've assumed you can't use them.
$arr = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14, 15, 16);
$max = count($arr);
$cols = 3;
$block = ceil($max / $cols);
for ($i = 0; $i < $block ; $i++) {
echo $arr[$i] . ' ';
for ($j = 1; $j < $cols; $j++) {
$nexKey = $i + $block * $j;
if (!isset($arr[$nexKey])) break;
echo $arr[$nexKey] . ' ';
}
echo '<br>';
}
NOTE : You can easily refactor the code inside the loop that uses $nexkey variable by making it into a loop itself so that it works for any number of columns. I've hardcoded it.
Uses loops now.

Categories