this is my sorted array
$sortedArray = array($value_one_fin,$value_two_fin,$value_three_fin,$value_four_fin,$value_five_fin,$value_six_fin,$value_seven_fin,$value_eight_fin,$value_nine_fin,$value_ten_fin,$value_eleven_fin,$value_twelve_fin,$value_thirteen_fin,$value_fourteen_fin,$value_fifteen_fin,$value_sixteen_fin,$value_seventeen_fin,$value_eighteen_fin,$value_nineteen_fin,$value_twenty_fin,$value_twentyone_fin,$value_twentytwo_fin,$value_twentythree_fin,$value_twentyfour_fin);
$result=findClosest($sortedArray,$num1);
this is the variable where i store my entered number
$num1
what i want to do is to display values from sorted array in the manner Buy at / above: 102.51 Targets: 105,107.58,110.19,112.83
Stoploss : 100
in the above example i have entered 100 as $num1. as per calc the $result is also 100 so it has to display next greater closest number which is 102.51 and in stop loss it shuld display next smaller closest number
CONDITION
1>if entered number $num1 is greater than $result then display the next greater closest number from sorted array
2>if entered number $num1 is equal to $result then display the next greater closest number from sorted array
pls help me with this how can i do this im doing this
Buy At/Above ";if ($num1>$result) {echo "$result ";}if ($num1=$result) {echo "$result ";}if ($num1<$result) {echo "$result ";}echo "for Targets"; if ($result<$value_one_fin){echo " $value_one_fin,";}
if ($result<$value_two_fin){echo " $value_two_fin,";}
if ($result<$value_three_fin){echo " $value_three_fin,";}
if ($result<$value_four_fin){echo " $value_four_fin,";}
if ($result<$value_five_fin){echo " $value_five_fin,";}
if ($result<$value_six_fin){echo " $value_six_fin,";}
if ($result<$value_seven_fin){echo " $value_seven_fin,";}
if ($result<$value_eight_fin){echo " $value_eight_fin,";}
if ($result<$value_nine_fin){echo " $value_nine_fin,";}
if ($result<$value_ten_fin){echo " $value_ten_fin,";}
if ($result<$value_eleven_fin){echo " $value_eleven_fin,";}
if ($result<$value_twelve_fin){echo " $value_twelve_fin,";}
if ($result<$value_thirteen_fin){echo " $value_thirteen_fin,";}
if ($result<$value_fourteen_fin){echo " $value_fourteen_fin,";}
if ($result<$value_fifteen_fin){echo " $value_fifteen_fin,";}
if ($result<$value_sixteen_fin){echo " $value_sixteen_fin,";}
if ($result<$value_seventeen_fin){echo " $value_seventeen_fin,";}
if ($result<$value_eighteen_fin){echo " $value_eighteen_fin,";}
if ($result<$value_nineteen_fin){echo " $value_nineteen_fin,";}
if ($result<$value_twenty_fin){echo " $value_twenty_fin,";}
if ($result<$value_twentyone_fin){echo " $value_twentyone_fin,";}
if ($result<$value_twentytwo_fin){echo " $value_twentytwo_fin,";}
if ($result<$value_twentythree_fin){echo " $value_twentythree_fin,";}
if ($result<$value_twentyfour_fin){echo " $value_twentyfour_fin";}
but its not working and also how to display STOP LOSS
Apologies if I've misunderstood the question - I'm not 100% clear what you're trying to achieve, but I'll try to be helpful.
It looks as though your array is sorted smallest to largest. So to find the first value greater than or equal to $num1, simply loop through your array from beginning to end, and stop when you find a value >= $num1 e.g.
function findClosest($sortedArray, $num1) {
foreach ($sortedArray as $value) {
if ($value >= $num1) {
return $value;
}
}
}
To find the closest number less than or equal to $num1, loop through the array from the end to the beginning e.g.
function findClosestLessThanOrEqual($sortedArray, $num1) {
for ($i = sizeOf($sortedArray) - 1; $i >= 0; $i--) {
if ($sortedArray[$i] <= $num1) {
return $sortedArray[$i];
}
}
}
There are faster ways to search a large array, but if your array only contains 24 values I think that's the simplest way.
Just needs a slight tweak to get the first 5 items >= $num1:
function find5Closest($sortedArray, $num1) {
for ($i = 0; $i < sizeOf($sortedArray); $i++) {
if ($sortedArray[$i] >= $num1) {
return array_slice($sortedArray, $i, 5);
}
}
}
This should return an array up to 5 values. If there are only 3 values >= $num1, then it will only return 3 values; if no values are >= $num1 it will return an empty array.
Similarly:
function find5ClosestLessThanOrEqual($sortedArray, $num1) {
for ($i = sizeOf($sortedArray) - 1; $i >= 0; $i--) {
if ($sortedArray[$i] <= $num1) {
return array_slice($sortedArray, min(0, $i-4), 5);
}
}
}
Related
The following is a multi-threaded program that does simple statistical computations on a user-defined array, I can't seem to figure out how to make the parent thread output the global variables defined in the worker threads, also how do I make a function that is invoked by using start() on a thread that points to that function to return a value?
import threading as th
# Function to give maximum in array
def maximum(arr):
global maxi
maxi = 0
for x in range(len(arr)):
if arr[x] > maxi:
maxi = arr[x]
#print ("%sMaximum value is: %s " % (" " , max) + "\n")
# Function to give minimum in array
def minimum(arr):
global mini
mini = 999999
for x in range(len(arr)):
if arr[x] < mini:
mini = arr[x]
#print ("%sMinimum value is: %s " % (" " , min) + "\n")
# Function to give average of an array
def average(arr):
count = len(arr)
global summ
summ = 0
for x in range(count):
summ = summ + arr[x]
avg = summ / count
#print ("%sAverage value is: %s " % (" " , avg) + "\n")
# Function to prompt user to input array of numbers
def defArray():
array = []
n = int(input("Please Enter the size of your Array of numbers: "))
for x in range(n):
s = input("Please Enter a number: ")
if check(s) == False:
print("Invalid User Input, Please make sure input is a number")
return
else:
array.append(float(s))
print("Your array is: ")
print(array)
return array
# Function to check if user input is correct
def check(item):
user_number = str(item)
if( user_number.isdigit()):
return True
else:
return False
# Section for calling the previous function to show execution
array = defArray()
t1 = th.Thread(target=maximum,args=[array])
t2 = th.Thread(target=minimum,args=[array])
t3 = th.Thread(target=average,args=[array])
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
while ($word = <STDIN>) {
$length = length($word) -1; # Subtract 1 for included newline char
$wordLength[$length]++;
}
print "Word length \t\t Occurrences \n\n";
for ( my $i =1; $i <= $#wordLength; $i++ ) {
if (not exists $wordLength[$i]) {
print "$i \t\t\t 0 \n";
}
else {
print "$i \t\t\t $wordLength[$i] \n";
}
}
This works great reading in a txt file and outputting as such:
Word Length Occurrence
1 27
2 104
3 1039
4 3505
5 7181
6 11765
7 15898
I am trying to get this to work using hash instead of an array but it doesn't seem to work. This is my attempt:
while ($word = <STDIN>) {
chomp($word);
$length = length($word);
$wordLength{$word} = "$length";
}
foreach $word (sort keys %wordLength) {
print "$word, $wordLength{$word}\n"; # print key and value
}
Why? Any array works great here.
my #occurrences_by_length;
while (my $word = <>) {
chomp($word);
my $length = length($word);
++$occurrences_by_length[$length];
}
print "Length Occurrences\n";
for my $length (1..$#occurrences_by_length) {
my $occurrences = $occurrences_by_length[$length]
or next;
printf "%6d %11d\n", $length, $occurrences;
}
A hash, while less efficient, could easily be used with next to no changes.
my %occurrences_by_length;
while (my $word = <>) {
chomp($word);
my $length = length($word);
++$occurrences_by_length{$length};
}
print "Length Occurrences\n";
for my $length (sort { $a <=> $b } keys(%occurrences_by_length)) {
my $occurrences = $occurrences_by_length{$length};
printf "%6d %11d\n", $length, $occurrences;
}
I'm trying to count the number of occupied spaces, then return that count from #turn_count. Right now I'm returning the orig array.
I'm also counting every iteration, instead of occupied indices.
board = [" ", " x", " ", " ", "O", "O", " ", " ", "X"]
def turn_count(board)
counter = 0
board.each do |index|
if index = "x" || index = "o"
counter += 1
puts "#{counter}"
end
end
end
turn_count(board)
You just need to return the value of counter at the end of your function and also change your = to ==.
= is for assignment. == is for comparison.
def turn_count(board)
counter = 0
board.each do |turn|
if turn.downcase == "x" || turn.downcase == "o"
counter += 1
puts "#{counter}"
end
end
counter
end
I've also added the downcase method so that you're comparison is consistent. Otherwise, if you're looking for x but the array contains an X, you won't get a match.
SIDENOTE:
I changed index to turn because what you're declaring for that each loop is not actually an index. It's the array element itself.
If you wanted to use the index in the loop, you'd need to do something like:
board.each_with_index do |turn, index|
SIDENOTE #2:
You could also do the each loop as a super clean one-liner:
board.each { |t| counter +=1 if ['x', 'o'].include?(t.downcase) }
Just another option. :-)
I'm trying to count the number of occupied spaces
board = [" ", " x", " ", " ", "O", "O", " ", " ", "X"]
board.count { |s| s != " " } #=> 4
[" ", " x", " ", " ", "O", "1O", " ", " ", "X"].count { |s| s =~ /\S/ }
#=> 4
You can do conditional counting for an array by passing a block to count that returns true for the elements you want to count.
In the above example the element is tested against a regex looking for anything other than whitespace in the field
If i understand your question correctly, i guess you want to return the count of occupied values.
To do this in ruby helpers are available. Like in your condition:
array = [" ", " x", " ", " ", "O", "O", " ", " ", "X"]
array.reject(&:blank?).count
It will return a count 4.
So here, reject will skip all the blank spaces and give a count of those elements are present.
It takes as input a number(string) and then the task is to remove n numbers to give a resulting lowest possible number, but you have to take care of the order, that is the constraint. You cannot change the order of the original numbers.
I wanted it to work in O(n), so I did this:
#!/usr/bin/perl
#lowestNS.pl
#Date: 2016-06-28
use warnings;
use strict;
use utf8;
(#ARGV == 2) or die "2 args needed";
my $num = $ARGV[0];
my $d = $ARGV[1];
my #arr;
int($num) > 0 or die "Enter positive number";
print "Number in: $num\nDel: $d\n";
if(int($num) == 0) {
print "Result: 0\n";
exit;
}
else {
my $str = $num;
#arr = split(//, $str); #/Split on each number
#Split and multiply by reverse index, to give precedence to the order of numbers
for(my $i = 0; $i < #arr; $i++) {
$arr[$i] *= (#arr - $i);
}
}
print "arr: " . join(',' , #arr) . "\n";
for (my $j = 0; $j < $d; $j++) {
my $max = $arr[0];
my $m_index = -1;
#replace nth maximum with -1
for (my $i = 0; $i < #arr; $i++) {
if($max <= $arr[$i]) {
$max = $arr[$i];
$m_index = $i;
}
}
$arr[$m_index] = -1;
}
#return all numbers with value other than -1
my $result = "";
for (my $i = 0; $i < #arr; $i++) {
if($arr[$i] != -1){
$result = $result . "" . $arr[$i]/(#arr - $i);
}
}
print "Result: $result\n";
It works in all cases, except, cases like:
Number = 765028321
Delete = 5
The problem is the removal of 765028321 when it should have removed the 765028321.
because 2*5 > 3*3.
I think, the algorithm is straightforward:
Suppose, N is the number of digits to delete;
1. Find the first smallest digit in the first N digits, delete digits to the left of it, decrease N by the number of digits deleted.
2. if N>0 take the digits to the right and repeat the steps above.
Of course, we need to check for marginal cases, and to ensure the final number does not start with 0.
Here is the code draft:
#!/usr/bin/perl
use strict;
use warnings;
my ($number, $del)=#ARGV;
my #num = $number=~m{.}g;
my $curpos=0;
my #finalnum;
for(;;) {
last if $del <=0 || $curpos+$del>=#num;
my $minpos=$curpos;
for (my $i=$curpos;$i<$curpos+$del+1 && $i < #num;$i++) {
if ($num[$i]<$num[$minpos] && !($curpos==0 && $num[$i]==0)) {
$minpos=$i;
}
}
push #finalnum, $num[$minpos];
$del-=($minpos-$curpos);
$curpos=$minpos+1;
}
push #finalnum, #num[$curpos+$del..$#num] if $curpos+$del < #num;
print join '', #finalnum;
A possible solution can be:
Create an array having count of all digits, eg. in your case, this array will look like: 1,1,2,1,0,1,1,1,1,0
Then, in a greedy manner, remove all big digits, as many as can be done. So, you remove 9s, but since its count is 0, you still need to remove 5 digits. Remove 8s, so you still need to remove 4 digits and so on.
This case is kind of trivial, so you will be left with 2 2's, 1 1's and 1 0's. In there were, say 3 4's also in the number, you will then need to remove 1 4. So, you will remove the leftmost of partial removals required.
Its a greedy approach, and works in O(n).
var a = [1,2,3]
var b = [1,2,3]
var c = [1,2,3,4]
Each array inside take out a number of a three digits.
A total of 36 kinds of combination of the above.
I want to compute the position of the each combination.
[1,1,1] position is 1
[1,1,2] position is 2
[2,2,4] position is?
I want to ask how much the position of a combination of them, is there a specific formula?
Write three nested for loops. First one is for array a,second for b and third for c. That way you will first change the c for a new permutation than b, than a. Before going to for loop declare a variable called count which is 1. At the third loop increase that variable by one. Example:
int first,second,third,count=1;
for(int i=0;i<a.size();i++)
{
first=a[i];
for(int k=0;k<b.size();k++)
{
second=b[k];
for(int g=0;g<c.size();g++)
{
third=c[g];
count=count+1; //count++
}
}
}
This is written in C++. But you get the idea.You can put if statements inbetween to find the number of the permutation that you are looking for.
var a = [1,2,3];
var b = [1,2,3];
var c = [1,2,3,4];
var all = [a,b,c];
var allCount = [b.length * c.length, c.length, 0];
function getIndex(combo) {
var count = 0;
for (var i = 0; i < combo.length; i++) {
var pos = all[i].indexOf(combo[i]);
if (pos < 0) {
throw new Error(combo[i] + "Not effective elements");
}
count += allCount[i] * pos;
}
count += combo[combo.length - 1];
return count;
}
console.log("index of [2,2,4] is " + getIndex([2,2,4]));
console.log("index of [1,1,1] is " + getIndex([1,1,1]));
console.log("index of [3,3,4] is " + getIndex([3,3,4]));
console.log("index of [1,2,3] is " + getIndex([1,2,3]));
console.log("index of [3,2,1] is " + getIndex([3,2,1]));
The output:
index of [2,2,4] is 20
index of [1,1,1] is 1
index of [3,3,4] is 36
index of [1,2,3] is 7
index of [3,2,1] is 29