For gnuplot, I have a large list of (randomly generated) numbers which I want to use as indices in a sum. How do I do it?
Here is what I mean. Let's say the list of numbers is
list = [81, 37, 53, 22, 72, 74, 44, 46, 96, 27]
I have a function
f(x,n) = cos(n*x)
I now want to plot the function, on the interval (-pi,pi) which is the sum of the f(x,n) as n runs through the numbers in list.
If you can control how your list looks like, try the following:
num = 10
# Let the numbers be in a space separated string.
# We can access the individual numbers with the word(string, index) function.
list = "81 37 53 22 72 74 44 46 96 27"
f(x,n) = cos(n*x)
set terminal pngcairo
set output "sum_cos.png"
set xrange [-pi:pi]
set samples 1000
# Build the plot command as a macro.
plt_cmd = ""
do for [n=1:num] {
plt_cmd = sprintf("%s + f(x,%s)", plt_cmd, word(list,n))
}
# Check what we have done so far.
print plt_cmd
titlestring = "{/Symbol S} cos(n_i*x), i = 1 ...".num
# Finally plot the sum by evaluating the macro.
plot #plt_cmd title titlestring
This is the result:
Related
A car dealer rents out the rare 1956 Aston Martin DBR1 (of which Aston Martin only ever made 5).
Since there are so many rental requests, the dealer decides to place bookings for an entire year in advance.
He collects the requests and now needs to figure out which requests to take.
Make a script that selects the rental requests such that greatest number of individual customers
can drive in the rare Aston Martin.
The input of the script is a matrix of days of the year, each row representing the starting and ending
days of the request. The output should be the indices of the customers and their day ranges.
It is encouraged to plan your code first and write your own functions.
At the top of the script, add a comment block with a description of how your code works.
Example of a list with these time intervals:
list = [10 20; 9 15; 16 17; 21 100;];
(It should also work for a list with 100 time intervals)
We could select customers 1 and 4, but then 2 and 3 are impossible, resulting in two happy customers.
Alternatively we could select requests 2, 3 and 4. Hence three happy customers is the optimum here.
The output would be:
customers = [2, 3, 4],
days = [9, 15; 16, 17; 21, 100]
All I can think of is checking if intervals intersect, but I have no clue how to make an overall optimal selection.
My idea:
1) Sort them by start date
2) Make an array of intersections for each one
3) Start to reject from the ones which has the biggest intersection array, removing rejected item from arrays of intersected units
4) Repeat point 3 until only units with empty arrays will remain
In your example we will get data
10 20 [9 15, 16 17]
9 15 [10 20]
16 17 [10 20]
21 100 []
so we reject 10 20 as it has 2 intersections, so we will have only items with empty arrays
9 15 []
16 17 []
21 100 []
so the search is finished
code on javascript
const inputData = ' 50 74; 6 34; 147 162; 120 127; 98 127; 120 136; 53 68; 145 166; 95 106; 242 243; 222 250; 204 207; 69 79; 183 187; 198 201; 184 199; 223 245; 264 291; 100 121; 61 61; 232 247'
// convert string to array of objects
const orders = inputData.split(';')
.map((v, index) => (
{
id: index,
start: Number(v.split(' ')[1]),
end: Number(v.split(' ')[2]),
intersections: []
}
))
// sort them by start value
orders.sort((a, b) => a.start - b.start)
// find intersection for each one and add them to intersection array
orders.forEach((item, index) => {
for (let i = index + 1; i < orders.length; i++) {
if (orders[i].start <= item.end) {
item.intersections.push(orders[i])
orders[i].intersections.push(item)
} else {
break
}
}
})
// sort by intersections count
orders.sort((a, b) => a.intersections.length - b.intersections.length)
// loop while at least one item still has intersections
while (orders[orders.length - 1].intersections.length > 0) {
const rejected = orders.pop()
// remove rejected item from other's intersections
rejected.intersections.forEach(item => {
item.intersections = item.intersections.filter(
item => item.id !== rejected.id
)
})
// sort by intersections count
orders.sort((a, b) => a.intersections.length - b.intersections.length)
}
// sort by start value
orders.sort((a, b) => a.start - b.start)
// show result
orders.forEach(item => { console.log(item.start + ' - ' + item.end)})
Wanted to expand/correct a little bit on the acvepted answer.
You should start by sorting by the start date.
Then accept the very last customer.
Go through the list descending from there and accept all request that do not overlap with the already accepted ones.
That's the optimal solution.
definition :
Palindromic Wing Primes (or PWP's for short) are numbers that
are primes, palindromic in base 10, and consisting of one central digit
surrounded by two wings having an equal amount of identical digits and
different from the central one. E.g.
101
99999199999
333333313333333
7777777777772777777777777
11111111111111111111111111111111411111111111111111111111111111111
A number is a palindromic wing prime if it is both a palindromic wing and prime. Here are the first several palindromic wing primes:
101, 131, 151, 181, 191, 313, 353, 373, 383, 727, 757, 787, 797, 919, 929, 11311, 11411, 33533, 77377, 77477, 77977, 1114111, 1117111, 3331333, 3337333, 7772777, 7774777, 7778777, 111181111, 111191111, 777767777, 77777677777,...
Please i need help with find the right algorithm or pseudo code for if a number is palindromic wing
and if someone could help me with guid me to more info about the Palindromic Wing Primes , their history and the last results and maybe help me with "mathematica Programming " that would be amazing
kind regards
Testing wing palindromes from wing length 1 to 20 using Mathematica.
sets = DeleteCases[Tuples[Range[0, 9], 2], {a_, a_} | {0, _}];
grow[n_] := Map[Flatten, {a = ConstantArray[#1, n], #2, a} & ### sets]
test[c_] := If[PrimeQ[k = FromDigits#c], AppendTo[output, k]]
run[from_, to_] := Do[test /# grow[i], {i, from, to}]
output = {};
run[1, 20]
101
131
151
181
191
...
111111111111111111131111111111111111111
777777777777777777797777777777777777777
77777777777777777777977777777777777777777
Interesting definition, first time that I hear about that.
Assuming that you know how to check if a number is palindromic and prime, here is some pseudo and python code
isPalindromicWing(N){
if isPalindromic(N){
num <- toString(N)
tam <- length(num)
if isOdd(tam) and lenght(toSet(num)) = 2{
middle <- num[ floor(tam/2) ]
if 1 = num.count(middle){
return True
}
}
}
return False
}
isPWP(N){
return isPalindromicWing(N) and isPrime(N)
}
I use sets to remove repetitions, and as the number can only have 2 different digit with lenght(toSet(num)) == 2 I check for that, then I take the middle number and check if only there is one of it in the number. The rest I think is self explanatory.
in python that is
def isPalindromic(N):
num = str(N)
return N == int( num[::-1] )
def isPalindromicWing(n):
if isPalindromic(n):
num = str(n)
tam = len(num)
if tam % 2 == 1 and len(set(num)) == 2:
middle = num[tam // 2]
if 1 == num.count(middle):
return True
return False
I don't know about "mathematica Programming", but is you understand this code surely you can do it in that too
I'm quite new to using MATLAB, and am still trying to understand how to make this particular function. I understand the formula for performing this on paper, but I'm having trouble translating it into the required MATLAB syntax.
How would a function be written such that it takes an array of numbers, and returns that array with unhappy numbers removed i.e. only happy numbers remaining?
EDIT - Proving and input and output
Input:
array = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
Output:
array = [7, 13, 19, 23, 31, 79, 97]
A happy number is such that a number's squared digits summed eventually equal to 1, or continue the process indefinitely as seen here.
I've written a small function (which might be further improved) to test the "happines" of a number.
Current version only works with scalar and one dim. array.
Input: the scalar or array to be tested
Output:
1) an index: happy (1) unhappy(0)
2) the list of happy number within the input set
3) the list of unhappy number within the input set
Running the function with the input specified in the question, the function returns:
function [is_happy,h_array,unh_array]=happy_number(in_val)
%
% Output:
% is_happy: 1 ==> the numberis happy
% 0 ==> the numberis unhappy
% h_array: happy numbers within input
% unh_array: unhappy numbers within input
%
% Input validity check (to be improved)
s=size(in_val);
if(iscell(in_val) || isstr(in_val) || isstruct(in_val) ...
|| ~find(s,1) || length(s) >= 3 || sum(floor(in_val)-in_val) ~= 0)
error('Only scalar or 1 dim array supported')
end
% Vars initialization
h_array=[];
unh_array=[];
h_array_cnt=1;
unh_array_cnt=1;
h_unh_cnt=1;
% Loop through input number
for i=1:length(in_val)
seq=[];
n=in_val(i);
seq_cnt=1;
seq(seq_cnt)=n;
% Test if the number is happy
while(n ~= 1 && n ~= 4)
% Decompose the number in its digits
sn=num2str(n);
nv=str2num(sn(:));
seq_cnt=seq_cnt+1;
seq(seq_cnt)=sum(nv.^2);
n=seq(seq_cnt);
end
% Set and display results
if(n == 1)
disp(['Number ' num2str(seq(1)) ' is HAPPY'])
is_happy(h_unh_cnt)=1;
h_unh_cnt=h_unh_cnt+1;
h_array(h_array_cnt)=seq(1);
h_array_cnt=h_array_cnt+1;
else
disp(['Number ' num2str(seq(1)) ' is UNHAPPY'])
is_happy(h_unh_cnt)=0;
h_unh_cnt=h_unh_cnt+1;
unh_array(unh_array_cnt)=seq(1);
unh_array_cnt=unh_array_cnt+1;
end
end
Hope this helps.
If you have the index of your unhappy numbers. You can remove them by writing :
array(unhappy_index) = [];
If you do not have the unhappy index, you can find them by using the followng command:
find()
[My first question of StackoverFlow, so, HI!]
I'm not sure of what the rules are around the place, but I have a straightforward question as follows...
The sequences 23, 45, 23 and 23, 45, 56, 23, 23, 56, 45, 23 are
examples of palindromes. The sequence 23, 45, 56 is not a palindrome.
The sequence 23, 32 is not a palindrome either. A sequence of length 1
is always a palindrome. A given sequence of integers can be broken up
into parts such that each of them is a palindrome. Consider the
sequence 34,45,34,56,34. This can be broken up into 3 palindrome
sequences with 34, 45, 34 constituting the first, 56 constituting the
second and 34 constituting the third. It can also be broken in 5
palindrome sequences each containing a single number.
We want to determine the smallest number K such that the given
sequence can be broken up into K palindrome sequences.
#include<iostream>
using namespace std;
int main() {
int n;
cin>>n;
int num[n];
for(int i=0;i<n;i++)
cin>>num[i];
int c[n];
int co=0;
for(int i=0;i<n;i++){
if(num[i]!=-1){
for(int j=i+1;j<n;++j){
if(num[i]==num[j]){
num[i]=num[j]=-1;
c[co]=j;
co++;
break;
}
}
}
}
if(n-co*2==0){
cout<<1;
}
else{
cout<<n-co*2;
}
}
I have a file which contains data in the following format 0,"20 300 40 12".
How can I read this data with sscanf function such that I store 0 in a separate variable and 20 300 40 12 in another variable. The problem is that the array within the " " changes its size, so I cannot use a fix length array. So I can have something like this within my file:
0,"20 300 40 12"
0,"20 300 43 40 12"
1,"22 40 12"
Can you give me a hint of how to read this?
Have you tried with this:
fid = fopen(filename,'r');
A = textscan(fid,'%d,%q','Delimiter','\n');
Here's another way to do it:
[a,b] = textread('ah.txt','%d,"%[^"]"');
fun = #(x) split(' ',x);
resb = cellfun(fun,b,'UniformOutput',false)
res = {a resb};
function l = split(d,s)
%split string s on string d
out = textscan(s,'%s','delimiter',d,'multipleDelimsAsOne',1);
l = out{1};